package com.jxb.netty.rocketmqNetty;

import com.jxb.netty.network.netty.basic.EchoClient;
import com.jxb.netty.network.netty.basic.EchoClientHandler;
import com.jxb.netty.rocketmqNetty.handler.NettyClientHandler;
import com.jxb.netty.rocketmqNetty.handler.NettyConnectManageHandler;
import com.jxb.netty.rocketmqNetty.handler.NettyServerHandler;
import com.jxb.netty.rocketmqNetty.serializable.CommandCustomHeader;
import com.jxb.netty.rocketmqNetty.serializable.RemotingCommand;
import com.jxb.netty.rocketmqNetty.serializable.RockEncode;
import com.jxb.netty.rocketmqNetty.serializable.RocketDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;

public class RocketNettyClient {

    private final int port;
    private final String host;

    public RocketNettyClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public static void main(String[] args) throws InterruptedException {
        new RocketNettyClient(6879,"127.0.0.1").start();
    }

    private void start() throws InterruptedException {
        //线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
//                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new RockEncode())
                                    .addLast(new RocketDecoder())
                                    .addLast(new IdleStateHandler(0,0,120))
                                    .addLast(new NettyConnectManageHandler())
                                    .addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture sync = b.connect(new InetSocketAddress(host,port)).sync();
            doWrite(sync.channel());
            sync.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }

    private void doWrite(Channel channel) {
        RemotingCommand cmd = new RemotingCommand();
        cmd.setCode(1);
        CommandCustomHeader customHeader = new CommandCustomHeader() {
            @Override
            public void checkFields() {
                System.out.println(111);
            }
        };
        cmd.setCustomHeader(customHeader);
        cmd.setVersion(3);
        channel.writeAndFlush(cmd);
    }


}
